package service

import (
	"errors"
	"fmt"
	"project1/db"
	"project1/dbmodel"
	"project1/middleware"
	"project1/util"
	"project1/validate"
	"strings"
	"time"
)

type UserService struct {
	CommService
}

// 登录接口
func (l *UserService) Login(body validate.LoginAccount) (any, error) {
	// 查询账号
	var user dbmodel.User
	if err := db.GormDB.Where("user_name = ? AND password = ?", body.UserName, body.Password).Find(&user).Error; err != nil || user.ID == 0 {
		return nil, errors.New("账号或密码错误")
	}

	// 验证账号是否冻结
	if user.Status == 2 {
		return "", errors.New("账号已冻结")
	}

	if user.Status == 3 {
		return "", errors.New("账号已禁用")
	}

	// 验证账号是否过期
	now := time.Now()

	user.LastLoginIp = body.IP // 最后登录IP
	user.OnlineStatus = 1      // 在线状态 0离线1在线

	// 判断最后登录时间是不是今天，不是则更新最后登录时间
	if user.LastLoginTime != now.Format("2006-01-02") {
		user.LoginDays += 1 // 登录天数+1
		user.LastLoginIp = body.IP
		user.LastLoginTime = now.Format("2006-01-02")
	}

	if err := db.GormDB.Save(&user).Error; err != nil {
		return "", errors.New("更新用户信息失败")
	}

	token, err := middleware.GenerateToken(int(user.ID))
	if err != nil {
		return nil, errors.New("生成token失败")
	}

	return token, nil
}

// 修改账号参数
func (l *UserService) ModifyAccount(body validate.AccountUpdata) (string, error) {
	// 查询账号
	var user dbmodel.User
	if err := db.GormDB.Where("user_name = ? AND password = ?", body.UserName, body.Password).Find(&user).Error; err != nil || user.ID == 0 {
		return "", errors.New("账号或密码错误")
	}

	// 验证账号是否冻结
	if user.Status == 2 {
		return "", errors.New("账号已冻结")
	}

	if body.Type == 1 {
		user.Password = body.Data // 密码
	} else {
		return "", errors.New("修改类型错误")
	}

	if err := db.GormDB.Save(&user).Error; err != nil {
		return "", errors.New("修改用户信息失败")
	}

	return "修改成功", nil
}

// 注册账号
func (l *UserService) Register(body validate.Register) (string, error) {
	// 开始一个新的事务
	tx := db.GormDB.Begin()
	var user dbmodel.User
	var carmineBodies dbmodel.Carmine

	// 验证账号是否存在
	err := tx.Where("user_name = ?", body.UserName).First(&user).Error
	if err == nil && user.ID != 0 {
		tx.Rollback() // 事务回滚
		return "", errors.New("账号已存在")
	}

	RoleId := 3
	if body.Carmine == dbmodel.SuperAdminCard {
		RoleId = 2 // 管理员
	} else {
		// 验证卡密是否有效
		err = CheckCard(body.Carmine)
		if err != nil {
			tx.Rollback() // 事务回滚
			return "", err
		}

		// 查询卡密
		if err := tx.Where("carmine = ?", body.Carmine).Find(&carmineBodies).Error; err != nil {
			tx.Rollback() // 事务回滚
			return "", errors.New("未查询到卡密")
		}
	}

	// 创建账号
	user, err = db.CreateUserP1("", body.UserName, body.Password, body.IP, "", uint(RoleId), carmineBodies.ID, carmineBodies.CreatedBy, carmineBodies.CreatedBy)
	if err != nil {
		tx.Rollback() // 事务回滚
		return "", errors.New("创建账号失败,Err:" + err.Error())
	}
	if err := tx.Create(&user).Error; err != nil {
		tx.Rollback() // 事务回滚
		return "", errors.New("注册失败")
	}

	if body.Carmine != dbmodel.SuperAdminCard {
		// 使用卡密
		carmineBodies.Ip = body.IP     // ip记录
		carmineBodies.Status = 1       // 卡密状态 设置为已使用
		carmineBodies.UserId = user.ID // 用户ID
		carmineBodies.Remark = "注册账号"  // 备注
		if err := tx.Save(&carmineBodies).Error; err != nil {
			tx.Rollback() // 事务回滚
			return "", errors.New("使用卡密失败")
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return "", errors.New("提交事务失败")
	}

	return "注册成功", nil
}

// DeleteAccount 删除账号
func (l *UserService) DeleteAccount(body *validate.DeleteAccount) (string, error) {
	// 开始事务
	tx := db.GormDB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback() // 恢复时回滚
		}
	}()

	// 查询账号
	var user dbmodel.User
	if err := tx.Table("user").Where("id = ?", body.ID).Find(&user).Error; err != nil || user.ID == 0 {
		tx.Rollback() // 查询失败时回滚
		return "", errors.New("未查询到账号")
	}

	// 删除卡密表
	if err := tx.Table("carmine").Where("user_id = ?", user.ID).Unscoped().Delete(&dbmodel.Carmine{}).Error; err != nil {
		tx.Rollback() // 删除失败时回滚
		return "", errors.New("删除卡密记录失败")
	}

	// 删除账号
	if err := tx.Table("user").Where("id = ?", body.ID).Unscoped().Delete(&dbmodel.User{}).Error; err != nil {
		tx.Rollback() // 删除失败时回滚
		return "", errors.New("删除账号失败")
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return "", errors.New("提交事务失败")
	}

	return "删除成功", nil
}

// 查询账号列表
func (l *UserService) GetAccountList(body *validate.AccountListParam) (any, error) {
	var data []dbmodel.User

	db := db.GormDB.Table("user")

	// 用户id查询
	if body.UserName != "" {
		db = db.Where("user_name LIKE ?", "%"+body.UserName+"%")
	}

	// 状态 0-全部 1-正常 2-拉黑
	if body.Status != 0 {
		db = db.Where("status = ?", body.Status)
	}

	// 在线状态 在线状态 不传-全部 0-离线 1-在线
	if body.OnlineStatus != nil {
		db = db.Where("online_status = ?", body.OnlineStatus)
	}

	// 登录开始时间
	if body.StartTime != "" {
		db = db.Where("last_login_time >= ?", body.StartTime)
	}

	// 登录结束时间
	if body.EndTime != "" {
		db = db.Where("last_login_time <= ?", body.EndTime)
	}

	err := db.Order("id desc").Find(&data).Error
	if err != nil {
		return nil, errors.New("查询失败:" + err.Error())
	}

	return dbmodel.ListData{
		Count: len(data),
		List:  data,
	}, nil
}

// Carmine 生成卡密
func (l *UserService) Carmine(body *validate.GenerateCard, CreatedBy uint) (string, error) {
	userid := "1"

	var carmineBodies []dbmodel.Carmine

	for i := 0; i < body.Count; i++ {
		carmineBody := dbmodel.Carmine{
			Carmine: util.GenerateMD5("1", userid), // 卡密
			Status:  0,                             // 卡密状态
			Remark:  body.Remark,                   // 备注
			ControlBy: dbmodel.ControlBy{
				CreatedBy: CreatedBy,
				UpdatedBy: CreatedBy,
				DeletedBy: 0,
			},
		}
		carmineBodies = append(carmineBodies, carmineBody)
		// 延迟1毫秒
		time.Sleep(time.Millisecond)
	}

	err := db.GormDB.Create(&carmineBodies).Error
	if err != nil {
		return "", errors.New("生成失败")
	}
	return "生成成功", nil
}

// 批量删除卡密
func (l *UserService) DeleteCarmine(body *validate.DeleteCards) (string, error) {
	cardIDList := strings.Split(body.Ids, ",")
	err := db.GormDB.Where("id in ?", cardIDList).Unscoped().Delete(&dbmodel.Carmine{}).Error
	return "删除成功", err
}

// 查询卡密
func (l *UserService) QueryCarmine(body *validate.QueryCards) (any, error) {
	var carmineBodies dbmodel.Carmine
	db := db.GormDB.Table("carmine")

	if body.Carmine != "" {
		db = db.Where("carmine = ?", body.Carmine)
	}

	err := db.Find(&carmineBodies).Error
	if err != nil {
		return carmineBodies, errors.New("未查询到卡密")
	}
	return carmineBodies, nil
}

// 查询卡密列表
func (l *UserService) QueryCardList() (carmineBodies any, err error) {
	type carlist struct {
		dbmodel.Carmine
		User dbmodel.User `json:"user" gorm:"foreignkey:CardId;references:ID"`
	}

	var carmineBodiesList []carlist

	db := db.GormDB.Table("carmine")

	// 连接表
	db = db.Joins("LEFT JOIN user as u ON u.card_id = carmine.id").
		Preload("User")

	err = db.Group("carmine.id").Order("carmine.id desc").Find(&carmineBodiesList).Error
	if err != nil {
		return carmineBodiesList, errors.New("未查询到卡密")
	}

	return dbmodel.ListData{
		Count: len(carmineBodiesList),
		List:  carmineBodiesList,
	}, nil
}

// 修改卡密类型
func (l *UserService) UpdateCardType(body *validate.UpdateCards, ip string, CreatedBy uint) (any, error) {
	var carmineBodies dbmodel.Carmine
	db := db.GormDB.Table("carmine")

	// 查询卡密信息
	db.Where("carmine = ?", body.Carmine).Find(&carmineBodies)

	carmineBodies.Ip = ip              // ip记录
	carmineBodies.Status = body.Status // 卡密状态 1:已使用 2:禁止使用

	err := db.Save(&carmineBodies).Error
	if err != nil {
		return nil, errors.New("操作卡密失败")
	}

	return carmineBodies, nil
}

// 卡密校验公共方法
func CheckCard(carmine string) error {
	var carmineBodies dbmodel.Carmine
	db := db.GormDB.Table("carmine")

	// 查询卡密信息
	err := db.Where("carmine = ?", carmine).Find(&carmineBodies).Error
	if err != nil || carmineBodies.ID == 0 {
		return errors.New("未查询到卡密")
	}

	if carmineBodies.Status == 1 {
		return errors.New("卡密已使用")
	}

	if carmineBodies.Status == 2 {
		return errors.New("卡密已禁止使用")
	}

	fmt.Printf("卡密校验成功\n")
	return nil
}
